<?php

namespace Traits;

use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

/**
 * 项目常规响应
 */
trait Response
{
    use Helpers;

    protected function success($data, $message = null)
    {
        $result = [
            'status_code' => 200
        ];

        if (is_array($data) || is_object($data)) {
            $result['data'] = $data;
            $_return = str_replace('\\', '', json_encode($result['data'], 320));

            if (strlen($_return) > 1000)
                $_return = Str::limit($_return, 1000) . '...';
        } else {
            $result['message'] = $data;
        }
        $message && $result['message'] = $message;
        if (!isset($_return)) {
            $_return = $result['message'];
        }
        if (!isset($result['data']))
            $result['data'] = [];
        return $result;
    }

    protected function fail($message, $statusCode = 421)
    {
        return $this->response->error($message, $statusCode);
    }

    /**
     * 统一对请求验证
     *
     * @param array $payload
     * @param array $rules
     * @return array
     */
    public function requestValidator($payload, $rules = [], $message = [])
    {
        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return $this->fail($validator->errors()->first());
        }
        return $payload;
    }
}
